package remote

import (
	"gitee.com/fierce_wolf/go-fox-edge-common/commLogger"
	"gitee.com/fierce_wolf/go-fox-edge-common/commMqtt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/String"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
)

type remoteCloud struct {
}

func (e *remoteCloud) BuildClientId(productId interface{}, deviceNum interface{}) string {
	return "S&" + String.ToString(deviceNum) + "&" + String.ToString(productId) + "&1"
}

func (e *remoteCloud) GetMqttClient(productId interface{}, deviceNum interface{}) *commMqtt.MqttClient {
	clientId := e.BuildClientId(productId, deviceNum)

	client := commMqtt.GetClient(clientId)
	if client != nil {
		return client
	}

	client = commMqtt.NewClient(clientId)
	client.Connect()
	return client
}

func (e *remoteCloud) SubscribeTopic(deviceName string, productId interface{}, deviceNum interface{}) {
	client := e.GetMqttClient(productId, deviceNum)

	// 检查：是否已经建立连接
	if !client.IsConnected() {
		return
	}

	// 订阅平台指令：/{productId}/{deviceNum}/function/get
	topic := "/" + String.ToString(productId) + "/" + String.ToString(deviceNum) + "/function/get"
	if !client.HasTopic(topic) {
		handler := &mqttHandler{}
		handler.deviceName = deviceName
		handler.productId = productId
		handler.deviceNum = deviceNum

		if client.Subscribe(topic, handler.MqttHandler()) == nil {
			commLogger.Info("MQTT订阅成功：" + deviceName + " ->" + topic)
		}
	}
}

func (e *remoteCloud) PublishDeviceValue(productId interface{}, deviceNum interface{}, values map[string]*edgeEntity.DeviceObjectValue, timestamp int64) {
	if Method.HasEmpty(values) {
		return
	}

	client := e.GetMqttClient(productId, deviceNum)

	// 检查：是否已经建立连接
	if client == nil || !client.IsConnected() {
		return
	}

	list := make([]map[string]interface{}, 0)
	for key, value := range values {
		data := make(map[string]interface{})
		data["id"] = key
		data["value"] = value.Value
		data["ts"] = timestamp

		list = append(list, data)
	}

	// 发布数据 (实时显示，属性/功能和监测数据，可定时上报监测数据)：/{productId}/{deviceNum}/property/post
	topic := "/" + String.ToString(productId) + "/" + String.ToString(deviceNum) + "/property/post"
	json := Json.BuildJson(list)
	client.Publish(topic, json, 60*1000)
}

func (e *remoteCloud) CloseNotExist(clientIds map[string]interface{}) {
	keys := commMqtt.Keys()
	for clientId, _ := range keys {
		_, ok := clientIds[clientId]
		if ok {
			continue
		}

		client := commMqtt.GetClient(clientId)
		if client == nil {
			continue
		}

		// 删除配置
		commMqtt.DelClient(clientId)

		// 注销订阅
		topics := client.Topics()
		client.Unsubscribes(topics...)

		// 删除连接
		commMqtt.DelClient(clientId)
	}
}
